package com.zdy.im.tio.command.handler;

import com.alibaba.fastjson.JSON;
import com.github.houbb.sensitive.word.core.SensitiveWordHelper;
import com.sixeco.framework.common.api.ApiDoc;
import com.sixeco.framework.core.redis.RedisClusterServer;
import com.sixeco.framework.core.redis.RedisKeys;
import com.sixeco.framework.core.redis.RedisUtil;
import com.sixeco.framework.util.ids.GlobalId;
import com.sixeco.framework.util.json.JsonUtils;
import com.zdy.im.chat.ChatMessageBody;
import com.zdy.im.chat.ChatMessageEnum;
import com.zdy.im.common.exception.ImException;
import com.zdy.im.core.ICommand;
import com.zdy.im.enums.ImMessageTypeEnum;
import com.zdy.im.tio.TioServerConfig;
import com.zdy.im.tio.command.AbstractCommandHandler;
import com.zdy.im.tio.command.Command;
import com.zdy.im.tio.command.ProtocolManager;
import com.zdy.im.tio.packets.JoinRoomRequestVo;
import com.zdy.im.user.dto.request.ImRoomChatMessageRequestDto;
import com.zdy.im.user.dto.response.ImRoomChatMessageResponseDto;
import com.zdy.im.user.service.ImRoomChatMessageService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.core.intf.Packet;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 
 * 版本: [1.0]
 * 功能说明: 加入群组消息cmd命令处理器
 * @Author 作者 : zdy
 * @CreateDate 创建时间: 2021-02-30
 */
@Component
@ApiDoc(module = "WebSocket 项目文档--加入群，绑定群关系",group = "SOCKET-GROUP")
public class JoinGroupReqHandler extends AbstractCommandHandler {
	
	private static Logger log = LoggerFactory.getLogger(JoinGroupReqHandler.class);

	@Autowired
	private RedisClusterServer redisClusterServer;
	@Autowired
	private ImRoomChatMessageService imRoomChatMessageService;

	@Override
	public ICommand command() {

		return Command.COMMAND_JOIN_GROUP_REQ;
	}

	public ICommand responseCmd() {
		return Command.COMMAND_JOIN_GROUP_RESP;
	}

	@ApiDoc(
			cmd = "7",methodType = "ws",
			value = "创建群聊/加入群聊消息协议 cmd=7",
			request = JoinRoomRequestVo.class,
			response = ChatMessageBody.class
	)
	@Override
	public Packet handler(Packet wsPacket, ChannelContext channelContext) throws ImException{
		//绑定群组;
		WsRequest packet = (WsRequest) wsPacket;
		if (packet.getBody() == null) {
			throw new ImException("body is null");
		}
		JoinRoomRequestVo vo = JsonUtils.parseObject(packet.getWsBodyText(), JoinRoomRequestVo.class);
		if (vo == null) {
			Packet respChatPacket = ProtocolManager.ResponsePacket.dataInCorrect(channelContext,responseCmd());
			return respChatPacket;
		}
		ChatMessageEnum enums = ChatMessageEnum.getEnum(vo.getType());
		if(enums == null){
			Packet respChatPacket = ProtocolManager.ResponsePacket.dataInCorrect(channelContext);
			return respChatPacket;
		}
		//加入群id
		Set<Long> userIds = new HashSet<>();
		if(StringUtils.isNotBlank(vo.getUserIds())){
			List<String> ids =  Arrays.asList(vo.getUserIds().split(","));
			userIds.addAll(ids.stream().map(a->{return Long.valueOf(a);}).collect(Collectors.toSet()));
		}
		if(CollectionUtils.isEmpty(userIds)){
			Packet respChatPacket = ProtocolManager.ResponsePacket.dataInCorrect(channelContext,responseCmd());
			return respChatPacket;
		}

		ChatMessageBody message = ChatMessageBody.build().clone(vo.getMessage());
		//content 内容就是用户名称，多个有逗号分隔
		String content = SensitiveWordHelper.replace(message.getContent());
		message.setMine(false);
		message.setMessageType(enums.getDbValue());//群聊
		message.setServiceTime(new Date());
		message.setGlobalId(GlobalId.get().nextId());
		message.setMessageId(message.getToId());
		message.setReadStatus(0);//未读
		message.setType(ImMessageTypeEnum.JOIN_ROOM.getKey());
		if(userIds.size() == 1){
			//单人
			message.setContent(message.getSendUserName()+" 邀请 "+content+" 加入群聊，新成员入群可查看所有历史消息");
		}else{
			//多人
			message.setContent(message.getSendUserName()+" 发起群聊，并邀请 "+content+" 加入群聊");
		}


		//todo 保存聊天记录;
		ImRoomChatMessageRequestDto chatRequestDto = ImRoomChatMessageRequestDto.build().clone(message);
		ImRoomChatMessageResponseDto result = imRoomChatMessageService.saveImRoomChatMessage(chatRequestDto);
		if(null == result){
			return ProtocolManager.ResponsePacket.dataInCorrect(channelContext,responseCmd());
		}
		userIds.forEach(userId->{
			//用户绑定群
			Tio.bindGroup(channelContext.tioConfig,String.valueOf(userId),String.valueOf(message.getToId()));
		});
		long groupId = message.getToId();
		WsResponse wsResponse = WsResponse.fromText(JsonUtils.toJson(message), TioServerConfig.CHARSET);
		Tio.sendToGroup(channelContext.tioConfig,String.valueOf(groupId), wsResponse);
		saveRedis(message);
		return ProtocolManager.ResponsePacket.success(channelContext,responseCmd());

	}

	private void saveRedis(ChatMessageBody message) {
		String formKey = RedisUtil.formatKey(RedisKeys.MQ_CONSUMER , "roomKey");
		redisClusterServer.hmset(formKey , String.valueOf(message.getMessageId()), JSON.toJSON(message).toString());

	}


}
